package com.shujia.spark.stream

import org.apache.spark.rdd.RDD
import org.apache.spark.streaming.dstream.{DStream, ReceiverInputDStream}
import org.apache.spark.{SparkConf, SparkContext}
import org.apache.spark.streaming.{Durations, StreamingContext}

object Demo4DStreamOnRDD {
  def main(args: Array[String]): Unit = {
    val conf: SparkConf = new SparkConf()
      .setMaster("local[2]")
      .setAppName("wc")

    val sc = new SparkContext(conf)

    /**
      * 创建spark streaming环境
      *
      */

    val ssc = new StreamingContext(sc, Durations.seconds(5))
    //1、读取数据
    val lineDS: ReceiverInputDStream[String] = ssc.socketTextStream("master", 8888)


    /**
      * 将DStream转换成RDD
      *
      * foreachRDD: 将DStream转换成RDD来使用，没有返回值
      *
      */

    lineDS.foreachRDD(rdd => {

      //使用rdd的api
      rdd
        .flatMap(_.split(","))
        .map((_, 1))
        .reduceByKey(_ + _)
        .foreach(println)
    })


    /**
      * transform: 将DS转换成RDD来使用，最后需要返回一个新的RDDD
      *
      */

    val resultDS: DStream[(String, Int)] = lineDS.transform(rdd => {
      val kvRDD: RDD[(String, Int)] = rdd
        .flatMap(_.split(","))
        .map((_, 1))

      //返回一个RDD
      kvRDD
    })

    resultDS.reduceByKey(_+_).print()


    ssc.start()
    ssc.awaitTermination()
    ssc.stop()

  }

}
